package com.tepth.busfix.main.home;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tepth.busfix.R;
import com.tepth.busfix.adapter.SimpleFragmentPagerAdapter;
import com.tepth.busfix.base.BaseActivity;
import com.tepth.busfix.base.BaseFragment;
import com.tepth.busfix.base.Event;
import com.tepth.busfix.base.OkBus;
import com.tepth.busfix.bean.reponse.BusInfo;
import com.tepth.busfix.bean.reponse.BusType;
import com.tepth.busfix.bean.reponse.TroubleContent;
import com.tepth.busfix.bean.request.StartRepair;
import com.tepth.busfix.config.SpKey;
import com.tepth.busfix.config.WorkStatusCode;
import com.tepth.busfix.data.DataProvider;
import com.tepth.busfix.main.login.LoginActivity;
import com.tepth.busfix.main.repair.RepairActivity2;
import com.tepth.busfix.main.setting.SettingActivity;
import com.tepth.busfix.tools.ActivityTaskManager;
import com.tepth.busfix.tools.SPUtils;
import com.tepth.busfix.view.dialog.DialogDelegate;
import com.tepth.busfix.view.dialog.SweetAlertDialogDelegate;
import com.zhangyu.zxing.CaptureActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.carbs.android.library.MDDialog;
import xyz.sahildave.widget.Utils;

/**
 * Created by 张宇 on 2017/3/10.
 */

public class HomeActivity extends BaseActivity implements HomeContract.View {

    public static final int REGISTER_CODE_CONFIRM_REPAIR = 100;
    public static final int REGISTER_CODE_CURRENT_REFRESH = 200;
    public static final int REGISTER_CODE_BACK_REFRESH = 300;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tabs)
    TabLayout tabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @BindView(R.id.tv_refresh)
    TextView tvRefresh;
    SimpleFragmentPagerAdapter fragmentAdapter;

    DialogDelegate dialogDelegate;

    private BusInfo mBusInfo;
    private HomePresenter mPresenter;

    private List<BusType> busTypes = new ArrayList<>();
    private List<BaseFragment> listFragments = new ArrayList<>();

    private boolean isNeedRefresh = true;
    private boolean isPortrait = true;

    @Override
    public int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    public void initView() {
        ActivityTaskManager.getActivityTaskManager().addActivity(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        initOrientation();
        //初始化搜索框
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_search:
                        onSearch(etSearch.getText().toString().trim());
                        break;
                    case R.id.menu_setting:
                        startActivity(new Intent(HomeActivity.this, SettingActivity.class));
                        break;
                }
                return true;
            }
        });
        etSearch.setHint("请输入车辆的编号");
        etSearch.setInputType(InputType.TYPE_CLASS_NUMBER);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearch(etSearch.getText().toString().trim());
                    Utils.hideInputMethod(v);
                    return true;
                }
                return false;
            }
        });
        initViewPager();
        dialogDelegate = new SweetAlertDialogDelegate(this);
        // mPresenter.getBusType();
        mPresenter.getOperationList();
        // dialogDelegate.showProgressDialog(false, "正在加载...");
        //注册确认维修操作
        OkBus.getInstance().register(REGISTER_CODE_CONFIRM_REPAIR, new Event() {
            @Override
            public void call(Message msg) {
                mBusInfo = (BusInfo) msg.obj;
                mPresenter.startRepair();
                dialogDelegate.showProgressDialog(true, getString(R.string._commiting));
            }
        }, OkBus.UI);
        //注册当前界面的刷新操作
        OkBus.getInstance().register(REGISTER_CODE_CURRENT_REFRESH, new Event() {
            @Override
            public void call(Message msg) {
                refresh();
            }
        }, OkBus.UI);
        //注册当前界面的刷新操作
        OkBus.getInstance().register(REGISTER_CODE_BACK_REFRESH, new Event() {
            @Override
            public void call(Message msg) {
                isNeedRefresh = true;
            }
        }, OkBus.UI);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        int mCurrentOrientation = getResources().getConfiguration().orientation;

        if (mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            for (BaseFragment fragment : listFragments) {
                fragment.onChange(true);
            }
        } else {
            for (BaseFragment fragment : listFragments) {
                fragment.onChange(false);
            }
        }
    }

    private void initOrientation() {
        int mCurrentOrientation = getResources().getConfiguration().orientation;
        if (mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            isPortrait = true;
        } else if (mCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            isPortrait = false;
        }
    }

    private void initViewPager() {
        fragmentAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), listFragments);
        viewPager.setAdapter(fragmentAdapter);
    }

    private void refresh() {
        mPresenter.getBusType();
        dialogDelegate.showProgressDialog(true, "正在加载...");
        isNeedRefresh = false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search, menu);
        return true;
    }

    @Override
    public void setPresenter() {
        mPresenter = new HomePresenter();
        HomeModel mModel = new HomeModel();
        mPresenter.setVM(this, mModel);
    }

    private void setupTabs(ArrayList<BusType> types) {
        try {
            ArrayList<BusInfo> allBusInfo = new ArrayList<>();
            //页面，数据源
            List<View> tabViews = new ArrayList<>();
            listFragments.clear();
            for (BusType busType : types) {
                ArrayList<BusInfo> busInfos = busType.getListRepair();
                listFragments.add(TabFragment.newInstance(busType.getWorkStatusCode(), busInfos, isPortrait));
                View v = LayoutInflater.from(this).inflate(R.layout.view_tab_title, null);
                TextView textView = (TextView) v.findViewById(R.id.tv_title);
                String size = busInfos.size() + "";
                int index[] = new int[1];
                String str = WorkStatusCode.getNameMap().get(busType.getWorkStatusCode())
                        + "(" + size + ")";
                index[0] = str.indexOf(size);
                SpannableStringBuilder style = new SpannableStringBuilder(str);
                int color = 0;
                switch (busType.getWorkStatusCode()) {
                    case WorkStatusCode.UNDER_PLAN:
                        color = getResources().getColor(R.color.bus_under_plan);
                        break;
                    case WorkStatusCode.FINISH_PLAN:
                        color = getResources().getColor(R.color.bus_finish_plan);
                        break;
                    case WorkStatusCode.READY_WORK:
                        color = getResources().getColor(R.color.bus_ready_work);
                        break;
                    case WorkStatusCode.UNDER_WORK:
                        color = getResources().getColor(R.color.bus_under_work);
                        break;
                    case WorkStatusCode.FINISH_WORK:
                        color = getResources().getColor(R.color.bus_finish_work);
                        break;
                    case WorkStatusCode.COMPLETE_WORK:
                        color = getResources().getColor(R.color.bus_complete_work);
                        break;
                }
                style.setSpan(new ForegroundColorSpan(color), index[0], index[0] + size.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                textView.setText(style);
                tabViews.add(v);
                allBusInfo.addAll(busInfos);
            }

            //构建全部数据
            listFragments.add(0, TabFragment.newInstance("0", allBusInfo, isPortrait));
            View v = LayoutInflater.from(this).inflate(R.layout.view_tab_title, null);
            TextView textView = (TextView) v.findViewById(R.id.tv_title);
            textView.setText("全部" + "(" + allBusInfo.size() + ")");
            tabViews.add(0, v);

            fragmentAdapter.notifyDataSetChanged();
            tabLayout.setupWithViewPager(viewPager);

            //设置自定义视图
            for (int i = 0; i < tabLayout.getTabCount(); i++) {
//            BadgeView badgeView = new BadgeView(this);
//            badgeView.setText("10");
//            badgeView.setTargetView(textView);
                TabLayout.Tab tab = tabLayout.getTabAt(i);
                tab.setCustomView(tabViews.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "数据请求失败!", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onNetworkError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
        showEmpty(true);
    }

    @Override
    public void onError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
        showEmpty(true);
    }

    @Override
    public void onTokenInvalid(String msg) {
        dialogDelegate.stopProgressWithWarning(msg, "请重新登录", new DialogDelegate.OnDialogListener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                intent.putExtra("reload", "reload");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(this, SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public String getBody() {
        StartRepair startRepair = new StartRepair();
        startRepair.setId(mBusInfo.getId());
        Gson gson = new Gson();
        return gson.toJson(startRepair);
    }

    @Override
    public void setBusType(ArrayList<BusType> list) {
        if(list != null) {
            busTypes.clear();
            busTypes.addAll(list);
            setupTabs(list);
            dialogDelegate.clearDialog();
            isNeedRefresh = false;
            showEmpty(false);
        }else{
            dialogDelegate.clearDialog();
            showEmpty(true);
        }
    }

    private void showEmpty(boolean isShow) {
        if (isShow) {
            tvRefresh.setVisibility(View.VISIBLE);
            viewPager.setVisibility(View.GONE);
        } else {
            tvRefresh.setVisibility(View.GONE);
            viewPager.setVisibility(View.VISIBLE);
        }
    }

    private void onSearch(String key) {
        ArrayList<BusType> list = new ArrayList<>();
        for (BusType type : busTypes) {
            BusType bustype = new BusType();
            bustype.setWorkStatus(type.getWorkStatus());
            bustype.setWorkStatusCode(type.getWorkStatusCode());
            List<BusInfo> busInfos = type.getListRepair();
            ArrayList<BusInfo> bs = new ArrayList<>();
            for (BusInfo busInfo : busInfos) {
                if (busInfo.getVehicleCode().contains(key)) {
                    bs.add(busInfo);
                }
            }
            bustype.setListRepair(bs);
            list.add(bustype);
        }
        setupTabs(list);
    }

    @Override
    public void setOperationList(List<TroubleContent.Operation> list) {
        if (list != null && !list.isEmpty())
            DataProvider.setOperationList(list);
    }


    @Override
    public void startRepairSucceed() {
        dialogDelegate.clearDialog();
        isNeedRefresh = true;
        RepairActivity2.startActivity(this, true, mBusInfo);
    }

    private static final int REQUEST_CODE_CAMERA = 2;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(this, CaptureActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
        OkBus.getInstance().unRegister(REGISTER_CODE_CONFIRM_REPAIR);
        OkBus.getInstance().unRegister(REGISTER_CODE_CURRENT_REFRESH);
        OkBus.getInstance().unRegister(REGISTER_CODE_BACK_REFRESH);
        mPresenter = null;
        dialogDelegate.clearDialog();
        dialogDelegate = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            String[] messageContent = new String[]{"是否退出"};
            new MDDialog.Builder(this)
                    .setMessages(messageContent)
                    .setTitle("提示")
                    .setNegativeButton(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    })
                    .setPositiveButton("退出", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            ActivityTaskManager.getActivityTaskManager().finishActivity();
//                            finish();
                            ActivityTaskManager.getActivityTaskManager().appExit(HomeActivity.this);

                        }
                    })
                    .setWidthMaxDp(600)
                    .setShowButtons(true)
                    .create()
                    .show();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedRefresh)
            refresh();
    }

    @OnClick(R.id.tv_refresh)
    public void onRefresh() {
        refresh();
    }
}
